import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class JedisDao {
    private final JedisPool jedisPool;

    private RuntimeSchema<User> schema = RuntimeSchema.createFrom(User.class);

    public JedisDao(String ip, int port) {
        jedisPool = new JedisPool(ip, port);
    }

    public User getUser(long id) {
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                String key = "user:" + id;
                //使用protostuff进行序列化而不用jdk自带的序列化，是为了提高效率，并且减少资源占用。
                byte[] bytes = jedis.get(key.getBytes());
                if (bytes != null) {
                    User user = schema.newMessage();
                    ProtostuffIOUtil.mergeFrom(bytes, user, schema);
                    return user;
                }
            } finally {
                jedis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String putUser(User user) {

        try {
            Jedis jedis = jedisPool.getResource();
            try {
                String key = "user:" + user.getId();
                byte[] bytes = ProtostuffIOUtil.toByteArray(user, schema,
                        LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
                //超时缓存
                int timeout = 60 * 60;//1小时
                String result = jedis.setex(key.getBytes(), timeout, bytes);
                return result;//正确时是OK,错误是错误信息
            } finally {
                jedis.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
